package main

import (
	"database/sql"
	"database/sql/driver"
	"flag"
	"fmt"
	"strings"
	"time"
	_ "github.com/go-sql-driver/mysql"
)
var(
	ip                            = flag.String("ip", "10.204.4.27", "the ip of need to catch.")
	port                          = flag.Int("port", 4000, "the port to need to catch.")
	user						  = flag.String("user","root","the database user.")
	password					  = flag.String("pass","","the database password.")
	db					 		  = flag.String("db","pay","the default database .")
	delay                          = flag.Int("delay", 10, "the minute of delay.")
	strBegin = ""
	exit chan int = make(chan int)
	strQuery = "SELECT ID, MESSAGE_ID FROM pay_purchase WHERE CREATED_TIME < '2019-07-14 00:00:00' AND BUSSINE_TYPE != 39 limit 0, 300;"
	updQuery = "update pay_purchase_temp set FC_RELATION_ID = '12345' where PERSONAL_ACCOUNT_ID = "
	origin int64 = 0
	flag1 bool = true
)
func main()  {
	flag.Parse()
	fmt.Printf("the target ip is : %s,the port is : %d,user is : %s,pass is : %s,db is : %s\n", *ip, *port,*user,*password,*db)
	for i:=0;i<100 ;i++  {
		go batch(i)
		//time.Sleep(2*time.Second)
	}
	for i:=0;i<100;i++{
		<- exit
		fmt.Println("over.")
	}
	fmt.Println("game over.")
	close(exit)
}

func batch(i int)  {

	dsn := fmt.Sprintf("%s:%s@%s(%s:%d)/%s",*user,*password,"tcp",*ip,*port,*db)
	//fmt.Println(dsn)
	DB,err := sql.Open("mysql",dsn)
	if err != nil{
		fmt.Printf("Open mysql failed,err:%v\n",err)
	}
	DB.SetConnMaxLifetime(1000*time.Minute)  //最大连接周期，超过时间的连接就close
	DB.SetMaxOpenConns(1) //设置最大连接数
	DB.SetMaxIdleConns(1) //设置闲置连接数

	for count:=0;count<*delay;count++{
		begin1 := time.Now().Unix()
		_,err1 :=DB.Exec(strQuery)
		end1 := time.Now().Unix()
		stamp := end1- begin1
		if end1-begin1 > 2{
			fmt.Println("execute time is:",i,stamp,time.Now())
		}
		if err1 != nil {
			if  err1 == driver.ErrBadConn || strings.Contains(err1.Error(),"close"){
				DB.Close()
				dsn := fmt.Sprintf("%s:%s@%s(%s:%d)/%s",*user,*password,"tcp",*ip,*port,*db)
				//fmt.Println(dsn)
				DB,err = sql.Open("mysql",dsn)
				if err != nil{
					fmt.Printf("Open mysql failed,err:%v\n",err)
					continue
				}
				DB.SetConnMaxLifetime(1000*time.Minute)  //最大连接周期，超过时间的连接就close
				DB.SetMaxOpenConns(1) //设置最大连接数
				DB.SetMaxIdleConns(1) //设置闲置连接数
				continue
			}
			fmt.Println("make an error.",i,stamp,time.Now(),err1)
		}
		//time.Sleep(time.Duration(*delay)*time.Minute)
	}
}